package com.bawei.module_home.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.lib_storage.database.HistoryManager
import com.bawei.lib_common.event.HistoryRefreshEvent
import com.bawei.module_home.widget.CommentDialog
import com.bawei.module_home.adapter.SimpleTypeAdapter
import com.bawei.module_home.adapter.SimpleVideoAdapter
import com.bawei.module_home.databinding.FragmentHomeBinding
import com.bawei.module_home.intent.SimpleTypeIntent
import com.bawei.module_home.state.SimpleTypeState
import com.bawei.module_home.viewmodel.HomeViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import kotlinx.coroutines.launch

private const val TAG = "HomeFragment"
class HomeFragment : BaseMVIFragment() {
    private lateinit var homeViewModel: HomeViewModel
    private val binding: FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }
    private var channelId = "94349546935"
    private var page = 0
    private var pageSize = 5
    private var mPosition = 0
    private lateinit var commentDialog: CommentDialog
    private val mSimpleVideoAdapter: SimpleVideoAdapter by lazy {
        SimpleVideoAdapter(
            onItemClick = { position ->
                val videoItem = mSimpleVideoAdapter.simpleVideoList[position]
                // 记录观看历史
                recordVideoHistory(videoItem)
                // 跳转到视频详情页
                ARouter.getInstance().build(Router.Ui.VIDEOETAIL_Actvivty).withSerializable("videoItem", videoItem).navigation()
            },
            onItemCommentClick = {
                commentDialog = CommentDialog(mSimpleVideoAdapter.simpleVideoList[it].item_id)
                commentDialog.show(this@HomeFragment.childFragmentManager, "getCommentList")
            }
        )
    }
    private val mSimpleTypeAdapter: SimpleTypeAdapter by lazy {
        SimpleTypeAdapter(
            onItemClick = {
                if (it != mPosition) {
                    mSimpleTypeAdapter.setPosition(it)
                    mSimpleTypeAdapter.notifyDataSetChanged()
                mPosition = it
                mSimpleVideoAdapter.clear()
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED){
                        homeViewModel.intents.send(SimpleTypeIntent.getSimpleVideoByChannelId(mSimpleTypeAdapter.simpleTypeList[mPosition].channelid,page,pageSize))
                    }
                }
            }
            }
        )
    }
    override fun generateViewModel() {
        homeViewModel = ViewModelProvider(this)[HomeViewModel::class.java]
    }

    override fun initView() {
        super.initView()
        initAdapter()
        //第一次打卡：正式初始化
        UMConfigure.init(requireActivity(),"686379d3bc47b67d839d0943","channel", UMConfigure.DEVICE_TYPE_PHONE,null)
        CrashReport.initCrashReport(requireActivity(), "c0befbb921", true);
        //事件埋点
        val map: MutableMap<String, Any> = HashMap()
        map["url"] = "123456" //广告链接
        map["type"] = "1" //广告类型
        MobclickAgent.onEventObject(requireActivity(), "ad_click", map)
        
        // 初始化红包组件
        binding.redPacketWidget.setStateCallback(object : com.bawei.lib_common.widget.RedPacketWidget.StateCallback {
            override fun completed() {
                LoggerUtils.d(TAG, "红包动画完成，恭喜获得红包！")
                // 设置红包数量
                binding.redPacketWidget.setTvNum(88)
                // 这里可以添加红包领取逻辑
            }
            
            override fun onRandomRedPacketGenerated(amount: Int) {
                LoggerUtils.d(TAG, "随机红包生成：+$amount")
                // 添加Toast提示，确保用户能看到
                android.widget.Toast.makeText(requireContext(), "恭喜获得随机红包：+$amount", android.widget.Toast.LENGTH_SHORT).show()
                // 领取红包：调用接口更新账户余额
                val id = AuthMMKV.accountId
                lifecycleScope.launch {
                    repeatOnLifecycle(Lifecycle.State.STARTED){
                        homeViewModel.intents.send(SimpleTypeIntent.updateAccountAmount(id,amount.toString()))
                        // 更新今日获得的奖励记录（用于显示）
                        AuthMMKV.homeMoney = amount
                    }
                }
            }
        })
        
        // 添加调试信息
        LoggerUtils.d(TAG, "RedPacketWidget initialized: ${binding.redPacketWidget != null}")
        
        // 移除红包组件点击事件，只通过滑动触发
        
        // 添加RecyclerView滑动监听
        setupScrollListener()
        
        // 调试：确保组件可见
        binding.redPacketWidget.visibility = android.view.View.VISIBLE
        LoggerUtils.d(TAG, "RedPacketWidget 已初始化，可见性: ${binding.redPacketWidget.visibility}")

    }
    
    /**
     * 设置滑动监听
     */
    private fun setupScrollListener() {
        // 为视频列表添加滑动监听
        binding.videoRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 停止滑动
                        binding.redPacketWidget.onScrollStop()
                        LoggerUtils.d(TAG, "列表停止滑动，红包动画停止")
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        // 开始滑动
                        binding.redPacketWidget.onScrollStart()
                        LoggerUtils.d(TAG, "列表开始滑动，红包动画开始")
                    }
                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 惯性滑动
                        binding.redPacketWidget.onScrollStart()
                        LoggerUtils.d(TAG, "列表惯性滑动，红包动画继续")
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 滑动过程中
                if (dx != 0 || dy != 0) {
                    LoggerUtils.d(TAG, "检测到滑动: dx=$dx, dy=$dy")
                    binding.redPacketWidget.onScroll()
                }
            }
        })
        
        // 为类型列表添加滑动监听
        binding.videoTypeRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 停止滑动
                        binding.redPacketWidget.onScrollStop()
                        LoggerUtils.d(TAG, "类型列表停止滑动，红包动画停止")
                    }
                    RecyclerView.SCROLL_STATE_DRAGGING -> {
                        // 开始滑动
                        binding.redPacketWidget.onScrollStart()
                        LoggerUtils.d(TAG, "类型列表开始滑动，红包动画开始")
                    }
                    RecyclerView.SCROLL_STATE_SETTLING -> {
                        // 惯性滑动
                        binding.redPacketWidget.onScrollStart()
                        LoggerUtils.d(TAG, "类型列表惯性滑动，红包动画继续")
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                // 滑动过程中
                if (dx != 0 || dy != 0) {
                    LoggerUtils.d(TAG, "检测到滑动: dx=$dx, dy=$dy")
                    binding.redPacketWidget.onScroll()
                }
            }
        })
    }
    
    override fun initData() {
        super.initData()
        //发送意图
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel.intents.send(SimpleTypeIntent.getSimpleType)
                homeViewModel.intents.send(SimpleTypeIntent.getSimpleVideoByChannelId(channelId,page,pageSize))
            }
        }
        binding.tbv.setDatas(
            listOf(
                "驷马难追",
                "杨过",
                "珠玉"
            )
        )
        binding.tbv.startViewAnimator()
        binding.srl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                mSimpleVideoAdapter.clear()
                page = 0
                lifecycleScope.launch {
                        homeViewModel.intents.send(SimpleTypeIntent.getSimpleVideoByChannelId(mSimpleTypeAdapter.simpleTypeList[mPosition].channelid ,page,pageSize))
                }
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page += 1
                lifecycleScope.launch {
                        homeViewModel.intents.send(SimpleTypeIntent.getSimpleVideoByChannelId(mSimpleTypeAdapter.simpleTypeList[mPosition].channelid,page,pageSize))
                }
            }
        })
    }

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return binding.root
    }

    override fun handleState() {
        //处理状态
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleTypeFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleTypeSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            mSimpleTypeAdapter.setSimpleTypeData(it.list!!)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                    // 每次收到新状态都结束刷新
                    binding.srl.finishRefresh()
                    binding.srl.finishLoadMore()
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                homeViewModel._simpleVideoFlow.collect {
                    when(it){
                        is SimpleTypeState.Init -> {
                            LoggerUtils.d(TAG,"初始化成功")
                        }
                        is SimpleTypeState.Empty -> {
                            LoggerUtils.d(TAG,"数据为空")
                        }
                        is SimpleTypeState.Failed -> {
                            LoggerUtils.d(TAG,"请求失败")
                        }
                        is SimpleTypeState.SimpleVideoSuccess -> {
                            Log.d(TAG, "handleState: ${it.list}")
                            mSimpleVideoAdapter.setSimpleVideoData(it.list!!)
                        }
                        else ->{
                            LoggerUtils.d(TAG,"其他状态")
                        }
                    }
                    // 每次收到新状态都结束刷新
                    binding.srl.finishRefresh()
                    binding.srl.finishLoadMore()
                }
            }
        }
    }
    private fun initAdapter() {
        mSimpleTypeAdapter.setupLayoutManager(binding.videoTypeRv)
        binding.videoTypeRv.adapter = mSimpleTypeAdapter
        mSimpleVideoAdapter.setupLayoutManager(binding.videoRv)
        binding.videoRv.adapter = mSimpleVideoAdapter
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::commentDialog.isInitialized) {
            commentDialog.dismiss()
        }
        if (::commentDialog.isInitialized){
            commentDialog.onDestroyView()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 停止红包动画
        binding.redPacketWidget.stop()
    }
    
    /**
     * 记录视频观看历史
     */
    private fun recordVideoHistory(videoItem: com.bawei.lib_common.entity.SimpleVideoEntityItem) {
        lifecycleScope.launch {
            try {
                val userId = "default_user" // 实际应用中应该从用户管理器中获取
                val success = HistoryManager.addHistory(
                    videoId = videoItem.id,
                    title = videoItem.title,
                    description = videoItem.description,
                    coverUrl = videoItem.videomainimag,
                    videoUrl = videoItem.videopath,
                    userId = userId
                )
                
                if (success) {
                    LoggerUtils.d(TAG, "成功记录观看历史: ${videoItem.title}")
                    // 使用EventBus发送刷新事件
                    org.greenrobot.eventbus.EventBus.getDefault().post(HistoryRefreshEvent())
                } else {
                    LoggerUtils.d(TAG, "记录观看历史失败: ${videoItem.title}")
                }
            } catch (e: Exception) {
                LoggerUtils.d(TAG, "记录观看历史异常")
            }
        }
    }
    
    /**
     * 添加测试历史记录（用于调试）
     */
    private fun addTestHistoryRecord() {
        lifecycleScope.launch {
            try {
                val userId = "default_user"
                val success = HistoryManager.addHistory(
                    videoId = 999,
                    title = "测试视频 - ${System.currentTimeMillis()}",
                    description = "这是一个测试视频，用于验证历史记录功能是否正常工作",
                    coverUrl = "https://example.com/test.jpg",
                    videoUrl = "https://example.com/test.mp4",
                    userId = userId
                )
                
                if (success) {
                    LoggerUtils.d(TAG, "测试历史记录添加成功")
                    // 使用EventBus发送刷新事件
                    org.greenrobot.eventbus.EventBus.getDefault().post(HistoryRefreshEvent())
                    // 显示成功提示
                    android.widget.Toast.makeText(requireContext(), "测试历史记录添加成功！", android.widget.Toast.LENGTH_SHORT).show()
                } else {
                    LoggerUtils.d(TAG, "测试历史记录添加失败")
                    android.widget.Toast.makeText(requireContext(), "测试历史记录添加失败！", android.widget.Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                LoggerUtils.d(TAG, "测试历史记录异常: ${e.message}")
                e.printStackTrace()
                android.widget.Toast.makeText(requireContext(), "测试历史记录异常: ${e.message}", android.widget.Toast.LENGTH_SHORT).show()
            }
        }
    }
}